import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class Receiver {
    private static ServerSocket[] serverSockets;
    private static Socket[] sockets;
    private static Receiver receiver;
    private static String[] PORTS;

    private Receiver() throws IOException {
        PORTS = Utilbll.getProperty("RECEIVE_PORT").split(",");
        serverSockets = new ServerSocket[PORTS.length];
        sockets = new Socket[PORTS.length];
        for (int i = 0; i < PORTS.length; i++) {
            serverSockets[i] = new ServerSocket(Integer.parseInt(PORTS[i]));
            sockets[i] = new Socket();
        }
    }

    public static Receiver getInstance() throws IOException {
        if (receiver == null) {
            receiver = new Receiver();
        }
        return receiver;
    }

    public void connect() throws IOException, ExecutionException, InterruptedException {
        for (int i = 0; i < Receiver.PORTS.length; i++) {
            sockets[i] = serverSockets[i].accept();
        }
    }

    public String[] getContent() throws IOException {
        String[] content = new String[Receiver.PORTS.length];
        for (int i = 0; i < Receiver.PORTS.length; i++) {
            InputStream is = sockets[i].getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            content[i] = br.readLine();
        }
        return content;
    }

    public HashMap<String, Integer> getMap(String[] jsonMaps) {
        HashMap<String, Integer> hm = new HashMap<>();
        for (String jsonMap : jsonMaps) {
            JSONObject jsonObject = JSONObject.parseObject(jsonMap);
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                String key = entry.getKey();
                Integer count = (Integer) entry.getValue();
                if (hm.containsKey(key)) {
                    hm.put(key, hm.get(key) + count);
                } else {
                    hm.put(key, count);
                }
            }
        }
        return hm;
    }
}
